package com.wxy.service;

import com.wxy.dao.GoodsDao;
import com.wxy.dao.SaleDao;
import com.wxy.entity.Goods;
import com.wxy.entity.Sale;
import com.wxy.exception.NotEnoughException;

public class BuyServiceImpl implements BuyService {

    private SaleDao saleDao;
    private GoodsDao goodsDao;


    public SaleDao getSaleDao() {
        return saleDao;
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    public GoodsDao getGoodsDao() {
        return goodsDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Override
    public void buy(Integer goodsId,Integer nums) {
        //记录购买信息
        Sale sale = new Sale();
        sale.setGid(goodsId);
        sale.setNums(nums);
        saleDao.insertSale(sale);

        //更新库存
        Goods goods = goodsDao.selectGoods(goodsId);
        if(goods == null){
            throw new NullPointerException("商品不存在");
        }else if(goods.getAmount() < nums){
            throw new NotEnoughException(goodsId+"的商品库存不足");
        }

        //修改
        Goods buyGoods = new Goods();
        buyGoods.setId(goodsId);
        buyGoods.setAmount(nums);
        goodsDao.updateGoods(buyGoods);

        System.out.println("商品已购买");
    }
}
